/* 实现物流系统WiFi通信*/
#include "wifi.h"
#include <string.h>
#include <stdio.h>
#include <ctype.h>

/* 网络状态标志 */
rt_bool_t network_available = RT_FALSE;
rt_bool_t mqtt_flag = RT_FALSE;
rt_bool_t mqtt_pub_in_progress = RT_FALSE;
rt_bool_t mqtt_pub_success = RT_FALSE;

/* WiFi配置参数 */
char ssid_str[64] = "ssidrtt21";
char pwd_str[64] = "psdrtt111";

/* MQTT配置参数 */
const char *client_id = "rjcs";
const char *product_key = "uU515Ic465";

const char *sign_params = "version=2018-10-31&res=products%%2FuU515Ic465%%2Fdevices%%2Frjcs&et=2088447118&method=md5&sign=AvXTr5zKPPT3n5siyV1vKg%%3D%%3D";
const char *server = "mqtts.heclouds.com";
int port = 1883;
const char *topic = "$sys/uU515Ic465/rjcs/thing/property/post/reply";
const char *publish_topic = "$sys/uU515Ic465/rjcs/thing/property/post";

/* 线程句柄 */
rt_thread_t mqtt_thread = RT_NULL;

/* UART4状态标志 */
static rt_bool_t uart4_initialized = RT_FALSE;

static rt_device_t uart4_dev = RT_NULL;
static char rx_buffer[256] = {0};
static uint16_t rx_len = 0;
char cmd[256] = {0};          // 命令缓冲区
rt_bool_t wifi_flag=RT_FALSE;

/* UART4接收回调函数 */
static rt_err_t uart4_rx_callback(rt_device_t dev, rt_size_t size)
{
    // 仅在UART4初始化成功时处理数据
    if (!uart4_initialized) return RT_ERROR;

    char ch;
    while (rt_device_read(dev, 0, &ch, 1) == 1)
    {
        rx_buffer[rx_len++] = ch;
        if (rx_len >= sizeof(rx_buffer) - 1) rx_len = 0;

        // 仅在发布过程中解析响应
        if (mqtt_pub_in_progress &&
            strstr(rx_buffer, "+MQTTSUBRECV") &&
            strstr(rx_buffer, publish_topic) &&
            strstr(rx_buffer, "\"code\":200"))
        {
            mqtt_pub_success = RT_TRUE;
            mqtt_pub_in_progress = RT_FALSE; // 结束发布状态
            LOG_I("mqt reply 200");
        }
    }
    return RT_EOK;
}

/* 初始化UART4 */
int uart4_init(void)
{
    if (uart4_dev != RT_NULL) {
        return RT_EOK; // 已初始化，直接返回
    }

    uart4_dev = rt_device_find("uart4");
    if (!uart4_dev) {
        LOG_E("wifi device not found");
        uart4_initialized = RT_FALSE;
        return RT_ERROR;
    }

    if (rt_device_open(uart4_dev, RT_DEVICE_FLAG_INT_RX) != RT_EOK) {
        LOG_E("Error: Open UART4 failed");
        uart4_initialized = RT_FALSE;
        return RT_ERROR;
    }

    if (rt_device_set_rx_indicate(uart4_dev, uart4_rx_callback) != RT_EOK) {
        LOG_E("Error: Set UART4 callback failed");
        rt_device_close(uart4_dev);
        uart4_dev = RT_NULL;
        uart4_initialized = RT_FALSE;
        return RT_ERROR;
    }

    LOG_I("wifi initialized successfully");
    uart4_initialized = RT_TRUE;
    return RT_EOK;
}

/* 发送AT命令并获取响应（新增UART4状态检查） */
int send_at_and_check(const char *cmd, const char *expect, rt_uint32_t timeout_ms)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("Error: UART4 not initialized, can't send AT command");
        return 0;
    }

    char temp_buf[512] = {0};

    /* 清空接收缓冲区 */
    rx_len = 0;
    memset(rx_buffer, 0, sizeof(rx_buffer));

    /* 发送命令 */
    rt_device_write(uart4_dev, 0, cmd, strlen(cmd));
    rt_device_write(uart4_dev, 0, "\r\n", 2);

    /* 等待响应 */
    rt_thread_mdelay(timeout_ms);

    /* 复制接收数据 */
    if (rx_len > 0 && rx_len < sizeof(temp_buf) - 1)
    {
        memcpy(temp_buf, rx_buffer, rx_len);
        temp_buf[rx_len] = '\0';
        /* 检查是否包含预期内容 */
        if (strstr(temp_buf, expect)) {
            rt_thread_mdelay(50);
            return 1;
        }
        else{
            LOG_W("at error: %s", temp_buf);
            return 0;
        }
    }
    return 0;
}

/* 检查WiFi状态（通过查找数字2判断） */
int check_wifi_state(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("Error: UART4 not initialized, can't check WiFi state");
        return 0;
    }

    char cmd[64] = "AT+CWSTATE?";
    rx_len = 0;
    memset(rx_buffer, 0, sizeof(rx_buffer));

    rt_device_write(uart4_dev, 0, cmd, strlen(cmd));
    rt_device_write(uart4_dev, 0, "\r\n", 2);
    rt_thread_mdelay(1000);

    if (rx_len > 0) {
        // 查找数字2（确保是独立的2，而非12、20等）
        char *ptr = rx_buffer;
        while ((ptr = strchr(ptr, '2')) != NULL) {
            // 确保2是一个独立的数字（前后不是数字字符）
            int is_standalone = 1;
            if (ptr > rx_buffer && isdigit(*(ptr-1))) is_standalone = 0;
            if (*(ptr+1) != '\0' && isdigit(*(ptr+1))) is_standalone = 0;

            if (is_standalone) {
                LOG_I("WiFi is connected (found standalone 2)");
                wifi_flag=RT_TRUE; //如果wifi能用 就不用4g
                return 1; // 找到独立的2，视为已连接
            }
            ptr++; // 继续查找下一个2
        }
        wifi_flag=RT_FALSE; //如果wifi能用 就不用4g
        LOG_E("WiFi is not connected (no standalone 2 found)");
    } else {
        LOG_E("No response from AT+CWSTATE?");
    }

    return 0;
}

/* 重新连接WiFi */
int reconnect_wifi(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("Error: UART4 not initialized, can't reconnect WiFi");
        return RT_ERROR;
    }

    LOG_W("WiFi not connected, reconnecting...");

    // 重置WiFi模式
    if (!send_at_and_check("AT+CWMODE=1", "OK", 1000)) {
        LOG_E("Set WiFi mode failed");
        return RT_ERROR;
    }
    rt_thread_mdelay(100);
    // 连接WiFi
    if (snprintf(cmd, sizeof(cmd), "AT+CWJAP=\"%s\",\"%s\"", ssid_str, pwd_str),
        !send_at_and_check(cmd, "OK", 10000)) {
        LOG_W("WiFi connection failed");
        return RT_ERROR;
    }
    return RT_EOK;
}

/* WiFi网络初始化 */
int wifi_network_init(void)
{
    if (uart4_init() != RT_EOK) {
        LOG_E("no wifi module");
        return RT_ERROR;
    }

    // 基础AT命令检查
    if (!send_at_and_check("AT", "OK", 1000)) {
        LOG_E("AT basic test failed");
        return RT_ERROR;
    }

    // 检查并连接WiFi
    if (!check_wifi_state()) {
        if (reconnect_wifi() != RT_EOK) {
            return RT_ERROR;
        }
    } else {
        LOG_I("WiFi already connected");
    }

    rt_thread_mdelay(10000); // 等待WiFi稳定
    return RT_EOK;
}

/* 检查MQTT连接状态（通过查找数字6判断） */
int check_mqtt_conn_state(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("wifi not initialized, can't check MQTT state");
        return 0;
    }

    char cmd[64] = "AT+MQTTCONN?";
    rx_len = 0;
    memset(rx_buffer, 0, sizeof(rx_buffer));

    rt_device_write(uart4_dev, 0, cmd, strlen(cmd));
    rt_device_write(uart4_dev, 0, "\r\n", 2);
    rt_thread_mdelay(1000);

    if (rx_len > 0) {
        // 查找数字6（确保是独立的6，而非16、60等）
        char *ptr = rx_buffer;
        while ((ptr = strchr(ptr, '6')) != NULL) {
            // 确保6是一个独立的数字（前后不是数字字符）
            int is_standalone = 1;
            if (ptr > rx_buffer && isdigit(*(ptr-1))) is_standalone = 0;
            if (*(ptr+1) != '\0' && isdigit(*(ptr+1))) is_standalone = 0;

            if (is_standalone) {
                LOG_I("MQTT is connected (found standalone 6)");
                return 1; // 找到独立的6，视为已连接
            }
            ptr++; // 继续查找下一个6
        }

        LOG_W("MQTT is not connected (no standalone 6 found)");
    } else {
        LOG_E("No response from AT+MQTTCONN?");
    }

    return 0;
}

/* 初始化MQTT连接 */
int mqtt_network_init(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("wifi not initialized, can't initialize MQTT");
        return RT_ERROR;
    }

    if (!check_mqtt_conn_state()) {
        LOG_W("MQTT not connected, connecting...");
        if (send_at_and_check(
            "AT+MQTTUSERCFG=0,1,\"rjcs\",\"uU515Ic465\",\"version=2018-10-31&res=products%2FuU515Ic465%2Fdevices%2Fgyxy&et=2058447118&method=md5&sign=cbZAfEB9TFrLZjs6dBfi0Q%3D%3D\",0,0,\"\"",
            "OK", 15000) &&
            send_at_and_check("AT+MQTTCONN=0,\"mqtts.heclouds.com\",1883,1", "+MQTTCONNECTED", 15000) &&
            send_at_and_check("AT+MQTTSUB=0,\"$sys/uU515Ic465/rjcs/thing/property/post/reply\",0", "OK", 15000)) {
            LOG_I("MQTT connected and subscribed");
            return RT_EOK;
        }
        else {
            LOG_E("MQTT setup failed");
            return RT_ERROR;
        }
    } else {
        LOG_I("MQTT already connected");
        return RT_EOK;
    }
}
void lcd_wire_statue(rt_bool_t flag1,rt_bool_t flag2);
/* 检查网络连接状态（WiFi+MQTT） */
void check_network_status(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("wifi not initialized, can't check network status");
        return;
    }

    int wifi_status = check_wifi_state();
    int mqtt_status = check_mqtt_conn_state();

    LOG_E("Network status: WiFi=%s, MQTT=%s",
              wifi_status ? "OK" : "ERROR",
              mqtt_status ? "OK" : "ERROR");

    // 如果网络不可用，停止MQTT线程
    if (!wifi_status || !mqtt_status) {
            network_available = RT_FALSE;
            mqtt_flag = RT_FALSE;
            lcd_wire_statue(network_available, mqtt_flag);
            LOG_E("Network error, MQTT stopped");
    }
    //需要连接wifi
    if(!wifi_status){wifi_network_init();}
    //只需要连接mqtt服务器
    if(!mqtt_status && wifi_status){mqtt_network_init();}
    // 如果网络从不可用变为可用，重启MQTT线程   现在问题杵在这里 就是无法重连mqtt服务器
    if (wifi_status && mqtt_status)  {
        if (network_available==RT_FALSE) {
            network_available = RT_TRUE;
            mqtt_flag = RT_TRUE;
            rt_kprintf("Network recovered, MQTT started\r\n");
        }
        lcd_wire_statue(network_available, mqtt_flag);
        //上传状态
    }
}

/* 发布MQTT数据 */
int publish_mqtt(const char *topic, const char *payload)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        LOG_E("wifi not initialized, can't publish MQTT");
        return 0;
    }

    mqtt_pub_in_progress = RT_TRUE;
    mqtt_pub_success = RT_FALSE;

    char pub_cmd[512];
    snprintf(pub_cmd, sizeof(pub_cmd), "AT+MQTTPUB=0,\"%s\",\"%s\",0,0", topic, payload);
    rt_device_write(uart4_dev, 0, pub_cmd, strlen(pub_cmd));
    rt_device_write(uart4_dev, 0, "\r\n", 2);
    LOG_I("WiFi_mqtt_up");

    // 等待响应
    rt_thread_mdelay(5000);

    // 检查是否成功
    if (!mqtt_pub_success) {
        LOG_E("MQTT publish failed! Checking network status...");
        check_network_status();
    }

    return mqtt_pub_success;
}

/* 上报数据线程 */
void mqtt_pub_thread(void *arg)
{
    while (1) {
        if (mqtt_flag && network_available) {
            char payload[512];
            snprintf(payload, sizeof(payload),
                "{\\\"id\\\":\\\"2450314406\\\"\\,"
                "\\\"params\\\":{\\\"rttdata\\\":{\\\"value\\\":{"
                "\\\"temp\\\":%.1f\\,\\\"humid\\\":%d\\,\\\"sw420\\\":%d\\,\\\"bat\\\":%d\\,\\\"Longit\\\":26.5551\\,"
                "\\\"Latit\\\":106.7778}}}}",
                (float)temperature + (float)temperature_x / 10.0,humidity,sw420_intensity,adc_data[1]);


           /* snprintf(payload, sizeof(payload),
                "{\\\"id\\\":\\\"2450314406\\\"\\,"
                "\\\"params\\\":{\\\"rttdata\\\":{\\\"value\\\":{\\\"sw420\\\":50}}}}");
            /*
            snprintf(payload, sizeof(payload),
                "{\\\"id\\\":\\\"2450314406\\\"\\,"
                "\\\"params\\\":{\\\"CurrentTemperature\\\":{\\\"value\\\":%.1f}}}",
                (float)temperature + (float)temperature_x / 10.0);*/
            if(publish_mqtt(publish_topic, payload) == RT_FALSE)
            {
                continue;
            }
            LOG_I("pub_data_ok");
            rt_thread_mdelay((up_period * 500+1000));
        }
        else{
            check_network_status();
            rt_thread_mdelay(20000);  // 15s检测一次网络
        }
    }
}

/* 主AT流程测试 */
void at_flow_test(void)
{
    // 初始化WiFi网络
    if (wifi_network_init() != RT_EOK) {
        LOG_E("WiFi initialization failed");
        return;
    }

    // 初始化MQTT网络
    if (mqtt_network_init() != RT_EOK) {
        rt_kprintf("MQTT initialization failed\r\n");
        return;
    }

    lcd_wire_statue(network_available, mqtt_flag);

    // 启动MQTT数据上报线程
    if (mqtt_thread == RT_NULL) {
        mqtt_thread = rt_thread_create("WiFi_up", mqtt_pub_thread, RT_NULL, 2048, 25, 10);
        if (mqtt_thread != RT_NULL) {
            rt_thread_startup(mqtt_thread);
            LOG_I("MQTT data publishing thread started");
        } else {
            rt_kprintf("Failed to create MQTT publishing thread\r\n");
        }
    }

    LOG_I("AT test completed");
}
MSH_CMD_EXPORT(at_flow_test, at);

/* 直接发送原始AT命令（用于调试） */
void send_raw_at_command(void)
{
    // 检查UART4是否初始化成功
    if (!uart4_initialized) {
        rt_kprintf("Error: UART4 not initialized, can't send raw AT command\r\n");
        return;
    }

    char expect[] = "OK";
    char response[256] = {0};
    uint16_t resp_len = 0;
    const char *at_cmd =  "AT+MQTTPUB=0,\"$sys/uU515Ic465/rjcs/thing/property/post\","
            "\"{\\\"id\\\":\\\"2450314406\\\"\\,\\\"params\\\":{\\\"txt\\\":{\\\"value\\\":23\\}}}\","
            "0,0\r\n";

    if (uart4_init() != RT_EOK) {
        rt_kprintf("UART4 init failed\r\n");
        return;
    }

    /* 清空接收缓冲区 */
    rx_len = 0;
    memset(rx_buffer, 0, sizeof(rx_buffer));

    /* 发送原始AT命令 */
    rt_device_write(uart4_dev, 0, at_cmd, strlen(at_cmd));
    /* 等待响应 */
    rt_thread_mdelay(5000);

    /* 读取响应 */
    if (rx_len > 0) {
        size_t copy_len = rx_len < sizeof(response) - 1 ? rx_len : sizeof(response) - 1;
        memcpy(response, rx_buffer, copy_len);
        response[copy_len] = '\0';

        rt_kprintf("rec (raw, len=%d): %s\r\n", (int)rx_len, response);

        if (strstr(response, expect)) {
            rt_kprintf("raw ok\r\n");
        } else {
            rt_kprintf("AT command failed. Full response: %s\r\n", response);
        }
    } else {
        rt_kprintf("No response received\r\n");
    }
}

/* MSH命令：发送原始AT命令（用于调试） */
void send_raw(int argc, char **argv)
{
    send_raw_at_command();
}
MSH_CMD_EXPORT(send_raw, Send raw AT command for MQTT publish);

/* MSH命令：手动检查MQTT连接状态 */
void mqtt_check(int argc, char **argv)
{
    check_mqtt_conn_state();
}
MSH_CMD_EXPORT(mqtt_check, Check MQTT connection status);

/* MSH命令：手动检查WiFi连接状态 */
void wifi_check(int argc, char **argv)
{
    check_wifi_state();
}
MSH_CMD_EXPORT(wifi_check, Check WiFi connection status);

/* 系统初始化 */
int system_init(void)
{
    // 初始化网络模块
    if (wifi_network_init() != RT_EOK) {
        LOG_E("WiFi initialization failed");
    }

    //检查一次网络情况
    check_network_status();

    // 启动MQTT线程
    if (mqtt_thread == RT_NULL) {
        mqtt_thread = rt_thread_create("WiFi_up", mqtt_pub_thread, RT_NULL, 4096, 27, 10);
        if (mqtt_thread != RT_NULL) {
            rt_thread_startup(mqtt_thread);
            LOG_I("MQTT data publishing thread started");
        } else {
            LOG_E("Failed to create MQTT publishing thread");
        }
    }
    return RT_EOK;
}
INIT_APP_EXPORT(system_init);
